package main

import (
	"context"
	"fmt"

	// "github.com/project-flogo/contrib/activity/log"
	"github.com/project-flogo/contrib/trigger/rest"
	"github.com/project-flogo/core/activity"
	"github.com/project-flogo/core/api"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/metadata"
	"github.com/project-flogo/core/engine"

	handler "gitee.com/shipnet/flogo_edge_model_handler"
)

func main() {

	app := myApp()

	e, err := api.NewEngine(app)

	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	engine.RunEngine(e)
}

func myApp() *api.App {
	app := api.NewApp()

	settings := &rest.Settings{
		Port: 3000,
	}
	trg := app.NewTrigger(&rest.Trigger{}, settings)
	h, _ := trg.NewHandler(&rest.HandlerSettings{
		Method: "POST",
		Path:   "/multimeters",
	})
	h.NewAction(RunActivities)

	mSettings := handler.Settings{
		MetricDataStore: map[string]interface{}{
			"addr": "192.168.1.17:6379",
			"db":   1,
		},
		EdgeChannelDataStore: map[string]interface{}{
			"addr": "192.168.1.17:6379",
			"db":   2,
		},
	}
	//store in map to avoid activity instance recreation
	act, err := api.NewActivity(&handler.Activity{}, mSettings)
	if err != nil {
		return app
	}
	activities = map[string]activity.Activity{"log": act}

	return app
}

var activities map[string]activity.Activity

func RunActivities(ctx context.Context, inputs map[string]interface{}) (map[string]interface{}, error) {

	trgOut := &rest.Output{}
	trgOut.FromMap(inputs)

	// msg, _ := coerce.ToString(trgOut.AnOutput)
	fmt.Printf("trgOut: %+v\n", trgOut.Content)
	m, err := coerce.ToObject(trgOut.Content)
	if err != nil {
		return nil, err
	}
	input := &handler.Input{}
	err = metadata.MapToStruct(m, input, true)
	if err != nil {
		return nil, err
	}
	r, err := api.EvalActivity(activities["log"], input)
	if err != nil {
		return nil, err
	}

	reply := &rest.Reply{Code: 200, Data: r}
	return reply.ToMap(), nil
}
